/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData } from '@amcax/base';
import { areLinesCoplanar } from '@app-base/common/utils/lines-coplanar';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { usePlaneContext } from './PlaneContext';
import { ChildPlaneCommandProps } from './types';

type FormData = {
  line1?: pickedLineData;
  line2?: pickedLineData;
  onlySamePlaneLines: boolean;
};

type Params = {
  mode: '2lines';
  line1: string;
  line2: string;
  onlySamePlaneLines: boolean;
};

// 创建平面-通过两条直线
export const PlaneTwoLine = ({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) => {
  const [formData, setFormData] = useState<FormData>({
    onlySamePlaneLines: true,
  });
  const { sharedLine, setSharedLine } = usePlaneContext();

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({ onlySamePlaneLines: true });
      return;
    }

    const { line1, line2, onlySamePlaneLines } = props.params as Params;

    await initEditDependency([line1, line2]);

    const lineObj1 = picker.generatePickObjByPickID(line1) as pickedLineData;
    const lineObj2 = picker.generatePickObjByPickID(line2) as pickedLineData;

    setFormData({
      line1: lineObj1,
      line2: lineObj2,
      onlySamePlaneLines: onlySamePlaneLines,
    });

    // 仅 line1 为共享线
    setSharedLine(lineObj1);
  }, [editDxid]);

  useEffect(() => {
    if (sharedLine && !formData.line1) {
      setFormData((prev) => ({ ...prev, line1: sharedLine }));
    }
  }, [sharedLine]);

  const isFormDataValid = (showTip = false) => {
    const { line1, line2, onlySamePlaneLines } = formData;

    if (line1 == null || line2 == null) {
      return false;
    }

    if (line1.edgeId === line2.edgeId) {
      if (showTip) MessageTip.warning('当前两条直线相同');
      return false;
    }

    if (onlySamePlaneLines) {
      const onSamplePlane = areLinesCoplanar(
        line1.edgeData[0],
        line1.edgeData[1],
        line2.edgeData[0],
        line2.edgeData[1],
      );
      if (!onSamplePlane) {
        if (showTip) MessageTip.warning('当前两条直线不在同一平面上');
        return false;
      }
    }

    return true;
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid(true)) {
      clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid(true)) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-plane-two-line', {
      commandName: 'CreatePlane',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { line1, line2, onlySamePlaneLines } = formData;

    return confirmCommand(
      {
        a: {
          mode: '2lines',
          line1: line1.edgeId,
          line2: line2.edgeId,
          onlySamePlaneLines: onlySamePlaneLines,
        },
      },
      preview,
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      line1: {
        type: 'string',
        format: PickInputRJSFFormat.PickLine,
      },
      line2: {
        type: 'string',
        format: PickInputRJSFFormat.PickLine,
      },
      onlySamePlaneLines: {
        type: 'boolean',
        title: '仅选择共面线',
        default: true,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        if (v.line1 && v.line1 !== formData.line1) {
          setSharedLine(v.line1);
        }

        setFormData(v);
      }}
      extraUiSchema={{
        line1: {
          'ui:placeholder': '请输入直线1',
          'ui:autofocus': true,
        },
        line2: {
          'ui:placeholder': '请输入直线2',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
